package com.mairuide.phone.calladdress;

import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.bill.utils.DateUtils;
import com.mairuide.phone.callanalysis.CallanalysisVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.utils.excel.ExcelExportUtil;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.entity.PageResult;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.callanalysis.service.CallAnalysisService;

/**
 * @Auther: zyj
 * @Date: 2018/12/21 16:48
 * @Description:
 */
@Controller
@RequestMapping(value = "/phoneAddress")
public class PhoneAddressController extends BaseController {
    @Autowired
    private AddressStatisticsService addressStatisticsService;
    @Autowired
    private CallAnalysisService callAnalysisService;
    @Resource
    private DataOperationLogService dataOperationLogService;

	@ModuleCode(value = "residence")
    @RequestMapping(method= RequestMethod.GET,value = "residence")
    public Object residence(ModelMap model){
        return "phonerecord/residenceStatistics";
    }
	@ModuleCode(value = "working")
    @RequestMapping(method= RequestMethod.GET,value = "working")
    public Object working(ModelMap model){
        return "phonerecord/workplaceStatistics";
    }
	@ModuleCode(value = "worked")
    @RequestMapping(method= RequestMethod.GET,value = "worked")
    public Object worked(ModelMap model){
        return "phonerecord/workedStatistics";
    }
	@ModuleCode(value = "specialDate")
    @RequestMapping(method= RequestMethod.GET,value = "specialDate")
    public Object specialDate(ModelMap model){
        return "phonerecord/specialDatesStatistic";
    }
    @RequestMapping(method= RequestMethod.GET,value = "callcomanalysis")
    public Object callcomanalysis(ModelMap model){
        return "phonerecord/callcommonanalysis";
    }
    @RequestMapping(method= RequestMethod.GET,value = "abnormaldetailDialog")
    public Object abnormaldetailDialog(ModelMap model){
        return "phone/abnormalphone/abnormaldetailDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "phonemapDialog")
    public Object phonemapDialog(ModelMap model){
        return "phone/phonemapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "phonedetailDialog")
    public Object phonedetailDialog(ModelMap model){
        return "phone/phonedetailDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "workedmapDialog")
    public Object workedmapDialog(ModelMap model){
        return "phonerecord/workedmapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "workplacemapDialog")
    public Object workplacemapDialog(ModelMap model){
        return "phonerecord/workplacemapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "specialdatemapDialog")
    public Object specialdatemapDialog(ModelMap model){
        return "phonerecord/specialdatemapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "meetmapDialog")
    public Object meetmapDialog(ModelMap model){
        return "phone/meet/meetmapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "trackdetailDialog")
    public Object trackdetailDialog(ModelMap model){
        return "phone/interactivetrajectory/trackdetailDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "trackmapDialog")
    public Object trackmapDialog(ModelMap model){
        return "phone/interactivetrajectory/trackmapDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "eachOtherDetailsDialog")
    public Object eachOtherDetailsDialog(ModelMap model){
        return "phone/eachohter/eachOtherDetailsDialog";
    }
    @RequestMapping(method= RequestMethod.GET,value = "phoneanalyticaltactics")
    public Object phoneanalyticaltactics(ModelMap model){
        return "phone/phoneanalyticaltactics";
    }

    //居住地分析
    @ResponseBody
    @RequestMapping(value="/residence",method= RequestMethod.POST)
    public Object residenceSearch(PhoneAddressDto dto){
        PageResult pageResult = null;
	    if (dto.getType()==1){
            List<MayBeAddr> list = addressStatisticsService.residenceStatisticsGeTian(dto);
            int start = (dto.getPage() - 1) * dto.getRows();
            int end = dto.getPage()* dto.getRows();
            pageResult = new PageResult(Long.valueOf(list.size()), list.subList(start,list.size()>end?end:list.size()));
        }else {
            List<MayBeAddr> list = addressStatisticsService.residenceStatistics(dto);
            int start = (dto.getPage() - 1) * dto.getRows();
            int end = dto.getPage()* dto.getRows();
            pageResult = new PageResult(Long.valueOf(list.size()), list.subList(start,list.size()>end?end:list.size()));
        }
        return  pageResult;
    }
    //居住地分析--地图详情
    @ResponseBody
    @RequestMapping(value="/residence_map",method= RequestMethod.POST)
    public Object residenceSearch_map(PhoneAddressDto dto){
        Map map = addressStatisticsService.residenceStatisticsMap(dto);
        return  map;
    }
    //工作日分析
    @ResponseBody
    @RequestMapping(value="/working",method= RequestMethod.POST)
    public Object workplaceStatistics(PhoneAddress pa,Integer page,Integer rows){
        PageResult pageResult = addressStatisticsService.workplaceStatistics(pa,page,rows);
        return  pageResult;
    }
    //工作日分析
    @ResponseBody
    @RequestMapping(value="/working_map",method= RequestMethod.POST)
    public Object working_map(PhoneAddress pa){
    	PageResult pageResult = addressStatisticsService.working_map(pa);
    	return  pageResult;
    }
    //双休日分析
    @ResponseBody
    @RequestMapping(value="/worked",method= RequestMethod.POST)
    public Object workedStatistics(PhoneAddress pa,Integer page,Integer rows){
        PageResult pageResult = addressStatisticsService.workedStatistics(pa,page,rows);
        return  pageResult;
    }
    //双休日分析
    @ResponseBody
    @RequestMapping(value="/worked_map",method= RequestMethod.POST)
    public Object worked_map(PhoneAddress pa){
    	PageResult pageResult = addressStatisticsService.worked_map(pa);
    	return  pageResult;
    }
    //特殊日期分析
    @ResponseBody
    @RequestMapping(value="/specialDate",method= RequestMethod.POST)
    public Object specialDate(PhoneAddress pa,Integer page,Integer rows){
        PageResult pageResult = addressStatisticsService.specialDatesStatistics(pa,page,rows);
        return  pageResult;
    }
    //特殊日期分析
    @ResponseBody
    @RequestMapping(value="/specialDate_map",method= RequestMethod.POST)
    public Object specialDate_map(PhoneAddress pa){
    	PageResult pageResult = addressStatisticsService.specialDate_map(pa);
    	return  pageResult;
    }
    //详情展示
    @ResponseBody
    @RequestMapping(value="/details",method= RequestMethod.POST)
    public Object details(PhoneAddress pa,Integer page,Integer rows){
        PageResult pageResult = addressStatisticsService.details(pa,page,rows);
        return  pageResult;
    }
    @RequestMapping(method= RequestMethod.POST,value = "/detailsExcel")
    @ResponseBody
    public void findDealFlowListExcel(@RequestBody PhoneAddress pa, HttpServletResponse response )throws Exception{
        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
        //建立新的sheet对象（excel的表单）
        Sheet sheet=wb.createSheet("通话详情");
        //在sheet里创建第二行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("机主号码");
        row2.createCell(1).setCellValue("呼叫类型");
        row2.createCell(2).setCellValue("对方号码");
        row2.createCell(3).setCellValue("通话日期");
        row2.createCell(4).setCellValue("通话时长");
        row2.createCell(5).setCellValue("基站号(CI)");
        row2.createCell(6).setCellValue("小区号(LAC)");
        row2.createCell(7).setCellValue("地址");
        //在sheet里创建第三行
        PageResult pageResult = addressStatisticsService.details(pa,1,Integer.MAX_VALUE);
        List<Map<String, Object>> content = pageResult.getRows();
        if (content!=null && content.size()>0){
            for (int i=0;i<content.size();i++){
                Map<String, Object> map = content.get(i);
                Row row3=sheet.createRow(i+1);
                row3.createCell(0).setCellValue((String) map.get("SERVICE_NUMBER"));
                row3.createCell(1).setCellValue(map.get("CALL_TYPE")==null?"":map.get("CALL_TYPE").toString().contains("0")?"主叫":"被叫");
                row3.createCell(2).setCellValue((String) map.get("PARTY_NUMBER"));
                row3.createCell(3).setCellValue(DateUtils.getDateString((Date) map.get("STARTING_TIME")));
                row3.createCell(4).setCellValue((String) map.get("TALK_TIME"));
                row3.createCell(5).setCellValue((String) map.get("CID"));
                row3.createCell(6).setCellValue((String) map.get("LAC"));
                row3.createCell(7).setCellValue((String) map.get("ADDRESS"));
            }
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "通话详情" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

    }

    //疑是工作地D3数据
    @ResponseBody
    @RequestMapping(value="/getD3Result",method= RequestMethod.POST)
    public Object getResidenceD3Result(PhoneAddress pa){
        List<Map<String, Object>> d3 = addressStatisticsService.getPhoneD3(pa);
        return  d3;
    }

    @ResponseBody
    @RequestMapping(value="/brokenline",method= RequestMethod.POST)
    public Object frequencyBrokenLine(BrokenLine bl){
        String caseId = request.getSession().getAttribute("caseId") == null ? "" : request.getSession().getAttribute("caseId").toString();
        Map<String,String> searchMap = new HashMap<>();
        searchMap.put("CASEMANAGE_ID",caseId);
        searchMap.put("time_type",bl.getTime_type());
        searchMap.put("SERVICE_NUMBER",bl.getSERVICE_NUMBER());
        searchMap.put("Time",bl.getTime());
        List frequency = callAnalysisService.frequencyBrokenLine(searchMap);
        return  frequency;
    }

    //导出Excel
    @RequestMapping("/exportExcel/{code}")
    @ResponseBody
    public void createExcel(HttpServletResponse response, PhoneAddress pa, @PathVariable("code")Integer code) throws Exception {

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle cellStyle = wb.createCellStyle();
        //设置居中:
        //设置字体:
        HSSFFont font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 12);//设置字体大小
        cellStyle.setFont(font);//选择需要用到的字体格式
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet("常用分析战法");
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow row1=sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell cell=row1.createCell(0);
        PageRequest pageRequest = new PageRequest(1,Integer.MAX_VALUE);
        PageResult pageResult = null;
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = null;
        //设置单元格内容
        switch (code){
            case 1: {//疑是居住地
                fileName = "疑是居住地" + dateFormat.format(new Date());
                cell.setCellValue("疑是居住地");
                PhoneAddressDto dto = new PhoneAddressDto();
                dto.setCaseId(pa.getCaseId());
                dto.setEndTime(pa.getEndTime());
                dto.setStartTime(pa.getStartTime());
                dto.setNight(pa.getNight());
                dto.setMorning(pa.getMorning());
                dto.setFrequency(pa.getFrequency());
//                dto.setPage(1);
                dto.setCardList(pa.getCardList());
//                dto.setRows(Integer.MAX_VALUE);

                List<MayBeAddr> list = addressStatisticsService.residenceStatistics(dto);
                new ExcelExportUtil(MayBeAddr.class).export(response,list,"疑似居住地分析.xlsx");
            }break;
            case 2: {//工作日
                fileName = "疑似工作地分析" + dateFormat.format(new Date());
                cell.setCellValue("疑似工作地分析");
                pageResult = addressStatisticsService.workplaceStatistics(pa,1,Integer.MAX_VALUE);
                List<Map<String,Object>> maps = pageResult.getRows();
                //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
                sheet.addMergedRegion(new CellRangeAddress(0,0,0,9));
                //在sheet里创建第二行
                HSSFRow row2=sheet.createRow(1);
                //创建单元格并设置单元格内容
                row2.createCell(0).setCellValue("机主号码");
                row2.createCell(1).setCellValue("基站号(CI)");
                row2.createCell(2).setCellValue("小区号(LAC)");
                row2.createCell(3).setCellValue("基站地址");
                row2.createCell(4).setCellValue("周一");
                row2.createCell(5).setCellValue("周二");
                row2.createCell(6).setCellValue("周三");
                row2.createCell(7).setCellValue("周四");
                row2.createCell(8).setCellValue("周五");
                row2.createCell(9).setCellValue("出现次数");

                //在sheet里创建第三行
                if (maps!=null && maps.size()>0){
                    for (int i=0;i<maps.size();i++){
                        Map<String,Object> map = maps.get(i);
                        HSSFRow row3=sheet.createRow(i+2);
                        row3.createCell(0).setCellValue((String)map.get("SERVICE_NUMBER"));
                        row3.createCell(1).setCellValue((String)map.get("CID"));
                        row3.createCell(2).setCellValue((String)map.get("LAC"));
                        row3.createCell(3).setCellValue((String)map.get("ADDRESS"));
                        row3.createCell(4).setCellValue(map.get("MONDAY").toString());
                        row3.createCell(5).setCellValue(map.get("TUESDAY").toString());
                        row3.createCell(6).setCellValue(map.get("WEDNESDAY").toString());
                        row3.createCell(7).setCellValue(map.get("THURSDAY").toString());
                        row3.createCell(8).setCellValue(map.get("FRIDAY").toString());
                        row3.createCell(9).setCellValue(map.get("COUNT").toString());
                    }
                }

            }break;
            case 3: {//双休
                fileName = "双休日通话分析" + dateFormat.format(new Date());
                cell.setCellValue("双休日通话分析");
                pageResult = addressStatisticsService.workedStatistics(pa,1,Integer.MAX_VALUE);
                List<Map<String,Object>> maps = pageResult.getRows();
                //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
                sheet.addMergedRegion(new CellRangeAddress(0,0,0,6));
                //在sheet里创建第二行
                HSSFRow row2=sheet.createRow(1);
                //创建单元格并设置单元格内容
                row2.createCell(0).setCellValue("机主号码");
                row2.createCell(1).setCellValue("基站号(CI)");
                row2.createCell(2).setCellValue("小区号(LAC)");
                row2.createCell(3).setCellValue("基站地址");
                row2.createCell(4).setCellValue("周六");
                row2.createCell(5).setCellValue("周日");
                row2.createCell(6).setCellValue("出现次数");

                //在sheet里创建第三行
                if (maps!=null && maps.size()>0){
                    for (int i=0;i<maps.size();i++){
                        Map<String,Object> map = maps.get(i);
                        HSSFRow row3=sheet.createRow(i+2);
                        row3.createCell(0).setCellValue((String)map.get("SERVICE_NUMBER"));
                        row3.createCell(1).setCellValue((String)map.get("CID"));
                        row3.createCell(2).setCellValue((String)map.get("LAC"));
                        row3.createCell(3).setCellValue((String)map.get("ADDRESS"));
                        row3.createCell(4).setCellValue(map.get("SATURDAY").toString());
                        row3.createCell(5).setCellValue(map.get("SUNDAY").toString());
                        row3.createCell(6).setCellValue(map.get("COUNT").toString());
                    }
                }
            }break;
            case 4: {//特殊日期
                fileName = "特殊日期通话分析" + dateFormat.format(new Date());
                cell.setCellValue("特殊日期通话分析");
                pageResult = addressStatisticsService.specialDatesStatistics(pa,1,Integer.MAX_VALUE);
                List<Map<String,Object>> maps = pageResult.getRows();
                //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
                sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
                //在sheet里创建第二行
                HSSFRow row2=sheet.createRow(1);
                //创建单元格并设置单元格内容
                row2.createCell(0).setCellValue("嫌疑人号码");
                row2.createCell(1).setCellValue("对方号码");
                row2.createCell(2).setCellValue("基站地址");
                row2.createCell(3).setCellValue("出现次数");

                //在sheet里创建第三行
                if (maps!=null && maps.size()>0){
                    for (int i=0;i<maps.size();i++){
                        Map<String,Object> map = maps.get(i);
                        HSSFRow row3=sheet.createRow(i+2);
                        row3.createCell(0).setCellValue((String)map.get("SERVICE_NUMBER"));
                        row3.createCell(1).setCellValue((String)map.get("PARTY_NUMBER"));
                        row3.createCell(2).setCellValue((String)map.get("BASE_STATION"));
                        row3.createCell(3).setCellValue(map.get("COUNT").toString());
                    }
                }
            }break;
            default: break;
        }

        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xls"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

    }


}
